import React from "react";
import {
  Button,
  Input,
  InputNumber,
  Form,
  Collapse,
  Divider,
  message,
} from "antd";
import { CaretRightOutlined } from "@ant-design/icons";

interface VideoMaterial {
  track_name: string;
  start_time: number;
  duration: number;
  relative_index: number;
  material: {
    path: string;
    name: string;
    crop_settings: any;
  };
}

interface VideoMaterialsPanelProps {
  videoMaterials: VideoMaterial[];
  filePaths: { [index: number]: { fullPath: string; displayName: string } };
  onVideoMaterialsChange: (materials: VideoMaterial[]) => void;
  onFilePathsChange: (paths: {
    [index: number]: { fullPath: string; displayName: string };
  }) => void;
  onSubmit: () => void;
}

const VideoMaterialsPanel: React.FC<VideoMaterialsPanelProps> = ({
  videoMaterials,
  filePaths,
  onVideoMaterialsChange,
  onFilePathsChange,
  onSubmit,
}) => {
  const updateVideoPath = (index: number, filePath: string) => {
    const updated = [...videoMaterials];
    updated[index] = {
      ...updated[index],
      material: {
        ...updated[index].material,
        path: filePath,
      },
    };

    if (
      filePath &&
      (!updated[index].material.name ||
        updated[index].material.name === "主背景视频" ||
        updated[index].material.name === `视频素材 ${index + 1}`)
    ) {
      const fileName =
        filePath.split("\\").pop() || filePath.split("/").pop() || filePath;
      updated[index].material.name = fileName.replace(/\.[^/.]+$/, "");
    }

    onVideoMaterialsChange(updated);

    onFilePathsChange({
      ...filePaths,
      [index]: {
        fullPath: filePath,
        displayName:
          filePath.split("\\").pop() || filePath.split("/").pop() || filePath,
      },
    });
  };

  const addVideoMaterial = () => {
    const newIndex = videoMaterials.length;
    const newMaterials = [
      ...videoMaterials,
      {
        track_name: `视频轨道 ${newIndex + 1}`,
        start_time: 2000000,
        duration: 4000000,
        relative_index: newIndex,
        material: {
          path: "",
          name: `视频素材 ${newIndex + 1}`,
          crop_settings: {
            upper_left_x: 0,
            upper_left_y: 0,
            upper_right_x: 1,
            upper_right_y: 0,
            lower_left_x: 0,
            lower_left_y: 1,
            lower_right_x: 1,
            lower_right_y: 1,
          },
        },
      },
    ];
    onVideoMaterialsChange(newMaterials);
  };

  const removeVideoMaterial = (index: number) => {
    if (videoMaterials.length <= 1) {
      message.warning("至少需要保留一个视频素材");
      return;
    }

    const updated = videoMaterials.filter((_, i) => i !== index);
    onVideoMaterialsChange(updated);

    const newPaths = { ...filePaths };
    delete newPaths[index];

    const reindexedPaths: {
      [index: number]: { fullPath: string; displayName: string };
    } = {};
    Object.entries(newPaths).forEach(([oldIndex, pathInfo]) => {
      const oldIdx = parseInt(oldIndex);
      const newIdx = oldIdx > index ? oldIdx - 1 : oldIdx;
      if (newIdx < updated.length) {
        reindexedPaths[newIdx] = pathInfo;
      }
    });

    onFilePathsChange(reindexedPaths);
  };

  const updateMaterialProperty = (
    index: number,
    property: string,
    value: any,
  ) => {
    const updated = [...videoMaterials];
    updated[index] = { ...updated[index], [property]: value };
    onVideoMaterialsChange(updated);
  };

  return (
    <div
      style={{
        height: "100%",
        overflow: "auto",
        padding: window.innerWidth < 768 ? "8px" : "0",
      }}
    >
      <Collapse
        bordered={false}
        defaultActiveKey={["0"]}
        expandIcon={({ isActive }) => (
          <CaretRightOutlined rotate={isActive ? 90 : 0} />
        )}
        size={window.innerWidth < 768 ? "small" : "middle"}
        items={videoMaterials.map((material, index) => ({
          key: index.toString(),
          label: (
            <span
              style={{
                fontWeight: 500,
                fontSize: window.innerWidth < 768 ? "12px" : "14px",
              }}
            >
              {material.track_name || `视频素材 ${index + 1}`}
            </span>
          ),
          children: (
            <div style={{ padding: window.innerWidth < 768 ? "4px" : "8px" }}>
              <Form.Item
                label={
                  <span
                    style={{
                      fontSize: window.innerWidth < 768 ? "12px" : "14px",
                    }}
                  >
                    视频文件路径
                  </span>
                }
                required
                validateStatus={material.material.path ? "success" : "error"}
                help={material.material.path ? undefined : "请输入视频文件路径"}
                style={{
                  marginBottom: window.innerWidth < 768 ? "12px" : "16px",
                }}
              >
                <Input
                  value={material.material.path}
                  onChange={(e) => updateVideoPath(index, e.target.value)}
                  placeholder="请输入完整的视频文件路径"
                  style={{
                    width: "100%",
                    fontSize: window.innerWidth < 768 ? "12px" : "14px",
                  }}
                  size={window.innerWidth < 768 ? "small" : "middle"}
                />
              </Form.Item>

              <Form.Item
                label={
                  <span
                    style={{
                      fontSize: window.innerWidth < 768 ? "12px" : "14px",
                    }}
                  >
                    开始时间 (秒)
                  </span>
                }
                style={{
                  marginBottom: window.innerWidth < 768 ? "12px" : "16px",
                }}
              >
                <InputNumber
                  value={material.start_time / 1000000}
                  onChange={(value) =>
                    updateMaterialProperty(
                      index,
                      "start_time",
                      (value || 0) * 1000000,
                    )
                  }
                  min={0}
                  step={0.5}
                  style={{
                    width: "100%",
                    fontSize: window.innerWidth < 768 ? "12px" : "14px",
                  }}
                  size={window.innerWidth < 768 ? "small" : "middle"}
                />
              </Form.Item>

              <Form.Item
                label={
                  <span
                    style={{
                      fontSize: window.innerWidth < 768 ? "12px" : "14px",
                    }}
                  >
                    持续时间 (秒)
                  </span>
                }
                style={{
                  marginBottom: window.innerWidth < 768 ? "12px" : "16px",
                }}
              >
                <InputNumber
                  value={material.duration / 1000000}
                  onChange={(value) =>
                    updateMaterialProperty(
                      index,
                      "duration",
                      (value || 0) * 1000000,
                    )
                  }
                  min={0.5}
                  step={0.5}
                  style={{
                    width: "100%",
                    fontSize: window.innerWidth < 768 ? "12px" : "14px",
                  }}
                  size={window.innerWidth < 768 ? "small" : "middle"}
                />
              </Form.Item>

              <Form.Item
                label={
                  <span
                    style={{
                      fontSize: window.innerWidth < 768 ? "12px" : "14px",
                    }}
                  >
                    相对层级
                  </span>
                }
                style={{
                  marginBottom: window.innerWidth < 768 ? "12px" : "16px",
                }}
              >
                <InputNumber
                  value={material.relative_index}
                  onChange={(value) =>
                    updateMaterialProperty(index, "relative_index", value || 0)
                  }
                  min={0}
                  style={{
                    width: "100%",
                    fontSize: window.innerWidth < 768 ? "12px" : "14px",
                  }}
                  size={window.innerWidth < 768 ? "small" : "middle"}
                />
              </Form.Item>

              <Button
                danger
                onClick={() => removeVideoMaterial(index)}
                style={{
                  width: "100%",
                  fontSize: window.innerWidth < 768 ? "12px" : "14px",
                }}
                size={window.innerWidth < 768 ? "small" : "middle"}
              >
                删除此素材
              </Button>
            </div>
          ),
        }))}
        style={{
          fontSize: window.innerWidth < 768 ? "12px" : "14px",
        }}
      />

      <Button
        type="dashed"
        onClick={addVideoMaterial}
        style={{
          width: "100%",
          marginTop: "16px",
          marginBottom: "20px",
          fontSize: window.innerWidth < 768 ? "12px" : "14px",
        }}
        size={window.innerWidth < 768 ? "small" : "middle"}
      >
        添加视频素材
      </Button>

      <Divider
        style={{ margin: window.innerWidth < 768 ? "12px 0" : "16px 0" }}
      />

      <Button
        type="primary"
        onClick={onSubmit}
        style={{
          width: "100%",
          fontSize: window.innerWidth < 768 ? "12px" : "14px",
        }}
        size={window.innerWidth < 768 ? "small" : "middle"}
      >
        创建项目
      </Button>

      {/* 响应式样式 */}
      <style>{`
        @media (max-width: 768px) {
          .ant-collapse-header {
            padding: 8px 12px !important;
            font-size: 12px !important;
          }
          
          .ant-collapse-content-box {
            padding: 8px !important;
          }
          
          .ant-form-item {
            margin-bottom: 12px !important;
          }
          
          .ant-form-item-label > label {
            font-size: 12px !important;
          }
          
          .ant-input, .ant-input-number {
            font-size: 12px !important;
          }
        }
        
        @media (max-width: 576px) {
          .ant-collapse-header {
            padding: 6px 8px !important;
          }
          
          .ant-form-item {
            margin-bottom: 8px !important;
          }
        }
      `}</style>
    </div>
  );
};

export default VideoMaterialsPanel;
